<template>
  <div>
    <page-list :x-uri="uri" :x-tabs="tabs" :doactions="doactions" :tree="true" :lazy="true" :lazy-fun="loadChild">
      <!-- 页面操作按钮 -->
      <template v-slot:page-button>
        <el-button v-auth="'user.admin.permission.create'" size="mini" type="primary" @click="create">新建节点</el-button>
      </template>
    </page-list>
  </div>
</template>

<script>
import PageList from '@public/template/page_list.vue';
export default {
  components: {
    PageList
  },
  inject: ['reload'],
  data() {
    return {
      uri: 'admin/user/permission/list',
      tabs: [
        {
          title: '节点管理',
          uri: '/user/permission',
          meta: {
            permission: 'user.admin.permission.list'
          }
        }
      ],
      doactions: [
        { title: '添加子节点', meta: { permission: 'user.admin.permission.create' }, callback: this.addChildren },
        { title: '编辑', meta: { permission: 'user.admin.permission.edit' }, callback: this.edit },
        { title: '删除', meta: { permission: 'user.admin.permission.delete' }, callback: this.deletePermission }
      ]
    };
  },
  methods: {
    create: function() {
      this.$router.push({ path: '/user/permission/create', query: { pid: 0 }});
    },
    addChildren: function({ row }) {
      this.$router.push({ path: '/user/permission/create', query: { pid: row.id }});
    },
    edit: function({ row }) {
      this.$router.push({ path: '/user/permission/' + row.id + '/edit' });
    },
    deletePermission: function({ row }) {
      this.$box
        .confirm('确认删除吗')
        .then(() => {
          this.$http.delete(
            '/admin/user/permission/' + row.id,
            {},
            response => {
              this.$message.success(response.msg, _ => {
                this.reload();
              });
            },
            error => {
              this.$message.error(error.msg);
            }
          );
        })
        .catch(() => {});
    },
    loadChild: function(row, treeNode, resolve) {
      this.$http.get(
        '/admin/user/permission/' + row.id + '/children',
        {
          pid: row.id
        },
        ({ data }) => {
          resolve(data);
        },
        response => {
          resolve([]);
          this.$message.error(response.msg);
        },
        false
      );
    }
  }
};
</script>
